package net.xdclass.component;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.SmsConfig;
import net.xdclass.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class SmsComponent {

    private static final String URL_TEMPLATE = "https://gyyyx1.market.alicloudapi.com/sms/smsSend?mobile=%s&templateId=%s&smsSignId=%s&param=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    @Async("threadPoolTaskExecutor")
    public void send(String mobile, String templateId, String param) {
        long beginTime = CommonUtil.getCurrentTimestamp();
        String url = String.format(URL_TEMPLATE, mobile, templateId, smsConfig.getSmsSignId(), param);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        long endTime = CommonUtil.getCurrentTimestamp();

        log.info("耗时={},url:{},body={}", endTime-beginTime, url, response.getBody());
        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("发送短信成功,响应信息:{}", response.getBody());
        } else {
            log.error("发送短信失败,响应信息:{}", response.getBody());
        }

    }

}
